<template>
  <div class="app-container">
   
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="处方类别" prop="drugInformationId">
        <el-select v-model="queryParams.drugInformationId" placeholder="处方类别" clearable style="width: 100px">
          <el-option
            v-for="dict in informationList"
            :key="dict.id"
            :label="dict.drugInformationName"
            :value="dict.id"
          />
        </el-select>
      </el-form-item>
 
      <el-form-item label="药品编码" prop="drugCode">
        <el-input
          v-model="queryParams.drugCode"
          placeholder="请输入药品编码"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="药品名称" prop="drugGenericName">
        <el-input
          v-model="queryParams.drugGenericName"
          placeholder="请输入药品名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="生产厂家" prop="drugManufacturer">
        <el-select v-model="queryParams.drugManufacturer" placeholder="请选择生产厂家" clearable style="width: 200px">
          <el-option
            v-for="dict in doctor_drug_manufacturer"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-table v-loading="loading" :data="drugList" @selection-change="handleSelectionChange">
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <el-table-column label="序号" align="center" prop="id" />
      <el-table-column label="药品编码" align="center" prop="drugCode" />
      <el-table-column label="药品名称" align="center" prop="drugGenericName" />
      <el-table-column label="规格" align="center" prop="drugSpecification" />
      <el-table-column label="处方分类" align="center" prop="drugInformationId">
        <template #default="scope">
           {{informationList.find(item => item.id == scope.row.drugInformationId)?.drugInformationName || '未知' }}
        </template>
      </el-table-column>  
    
      <el-table-column label="剂型" align="center" prop="drugForm" >
        <template #default="scope">
          <dict-tag :options="doctor_drug_form" :value="scope.row.drugForm"/>
        </template>
      </el-table-column>
      <el-table-column label="生产厂家" align="center" prop="drugManufacturer">
        <template #default="scope">
          <dict-tag :options="doctor_drug_manufacturer" :value="scope.row.drugManufacturer"/>
        </template>
      </el-table-column>
      <el-table-column label="库存" align="center" prop="drugInventory" >
        <template #default="scope">
          <span 
                :style="{ 
                  color:'red',
                  fontWeight:'600',
                  fontSize: '18px',
                  display: 'inline-flex',
                  alignItems: 'center',
                  gap: '4px'
                }"
              >
                {{ scope.row.drugInventory }}
                <dict-tag 
                  :options="doctor_packaging_unit" 
                  :value="scope.row.packagingUnit"
                  style="margin-left: 6px"
                />
              </span>
         
        </template>
      </el-table-column>
      <el-table-column label="采购价" align="center" prop="purchasePrice" >
        <!-- <template #default="scope">
          {{(scope.row.purchasePrice)*(scope.row.drugInventory)}}
        </template> -->
      </el-table-column>
    
      <el-table-column label="零售价" align="center" prop="retailPrice" />
     
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="250" >
        <template #default="scope">
          <el-button link type="primary" icon="Delete" @click="handleUpdate(scope.row)">查看详细</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 详细 -->
    <el-dialog :title="title" v-model="open" width="1000px" append-to-body>
      <div class="order-info" :model="form"  >
        <el-row :gutter="20">
          <el-col :span="6">
            <div class="info-item">
              <label>药品编码：</label>
              <div >{{ form.drugCode }}</div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="info-item">
              <label>药品名称：</label>
              <!-- <dict-tag :options="doctor_drug_category" :value="form.supplier"/> -->
              <div >{{ form.drugGenericName }}</div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="info-item">
              <label>收费类型：</label>
              <div >{{informationList.find(item => item.id == form.drugInformationId)?.drugInformationName || '未知' }}</div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="info-item">
              <label>药品规格：</label>
              <div >{{ form.drugSpecification }}</div>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="6">
            <div class="info-item">
              <label>药品剂型：</label>
              <dict-tag :options="doctor_drug_form" :value="form.drugForm"/>
              <!-- <div >{{ form.drugForm }}</div> -->
            </div>
          </el-col>
          <el-col :span="6">
            <div class="info-item">
              <label>生产厂家：</label>
              <dict-tag :options="doctor_drug_manufacturer" :value="form.drugManufacturer "/>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="info-item">
              <label>库存：</label>
              <div >{{form.drugInventory }}</div>
            </div>
          </el-col>
        </el-row>
        
      </div> 
      <h2>库存明细</h2>
     
      <el-table v-loading="loading" :data="filteredInventoyList">
          <!-- <el-table-column label="序号" align="center"/> -->
          <el-table-column label="单号" align="center"  >
            <template #default="scope">
              {{ scope.row.warehousing?.warehousingOrderId || scope.row.drugsOut?.drugsOutId }}
            </template>
          </el-table-column>
          <el-table-column label="操作时间" align="center" >
            <template #default="scope">
              {{ scope.row.warehousing?.documentCreationDate || scope.row.drugsOut?.drugsOutCreationDate }}
            </template>
          </el-table-column>
          <el-table-column label="类型" align="center">
            <template #default="scope">
              {{ scope.row.warehousing?.warehousingType || scope.row.drugsOut?.drugsOutType }}
            </template>
          </el-table-column>
          <el-table-column label="数量" align="center">
            <template #default="scope">
              <span 
                :style="{ 
                  fontWeight:'600',
                  fontSize: '18px',
                  color: scope.row.warehousing ? '#67C23A' : '#F56C6C',
                  display: 'inline-flex',
                  alignItems: 'center',
                  gap: '4px'
                }"
              >
                {{ scope.row.warehousing ? '+' : '-' }}{{ scope.row.quantity }}
                <dict-tag 
                  :options="doctor_packaging_unit" 
                  :value="scope.row.unit"
                  style="margin-left: 6px"
                />
              </span>
            </template>
          </el-table-column>
          <el-table-column label="采购金额（元）" align="center">
            <template #default="scope">
                {{ scope.row.purchaseAmount}} 
            </template>
          </el-table-column>
          <el-table-column label="零售金额（元）" align="center">
            <template #default="scope">
                {{ scope.row.retailAmount}} 
            </template>
          </el-table-column>
         
      </el-table>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">返回</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Drug">
import { listIntermediate,selectDrugByCode } from "@/api/drug/intermediate";
import { listDrug, getDrug, delDrug, addDrug, updateDrug,getDrugCode } from "@/api/drug/drug";
import { listInformation } from "@/api/drug/information";
import { selectOutDrugByCode } from "@/api/drug/outIntermediate";

const { proxy } = getCurrentInstance();
const { doctor_packaging_unit, doctor_drug_manufacturer, doctor_drug_form, sys_common_status, sys_yes_no, doctor_drug_category, doctor_invoice_item, doctor_drug_usage } = proxy.useDict('doctor_packaging_unit', 'doctor_drug_manufacturer', 'doctor_drug_form', 'sys_common_status', 'sys_yes_no', 'doctor_drug_category', 'doctor_invoice_item', 'doctor_drug_usage');

const drugList = ref([]);
// const InventoyList = ref([]);
const informationList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const daterangeCreationTime = ref([]);
const InventoyList = ref([]);

const filteredInventoyList = computed(() => {
  return InventoyList.value.filter(item => 
    item.warehousing?.auditStatus== '1'|| item.drugsOut?.auditStatus== '1'
  );
});



const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    drugInformationId: null,
    drugCode: null,
    drugGenericName: null,
    drugManufacturer: null,
    drugStatus: null,
    creationTime: null,
    drugInventory:null
  },
  rules: {
    drugInformationId: [{ required: true, message: "处方类别不能为空", trigger: "change" }],
    drugCode: [{ required: true, message: "药品编码不能为空", trigger: "blur" }],
    drugGenericName: [{ required: true, message: "药品通用名不能为空", trigger: "blur" }],
    drugCategory: [{ required: true, message: "药品分类不能为空", trigger: "change" }],
    drugSpecification: [{ required: true, message: "药品规格不能为空", trigger: "blur" }],
    invoiceItem: [{ required: true, message: "发票项目不能为空", trigger: "change" }],
    drugManufacturer: [{ required: true, message: "生产厂家不能为空", trigger: "change" }],
    purchasePrice: [{ required: true, message: "采购价不能为空", trigger: "blur" }],
    retailPrice: [{ required: true, message: "零售价不能为空", trigger: "blur" }],
    drugStatus: [{ required: true, message: "药品状态不能为空", trigger: "change" }],
    otcFlag: [{ required: true, message: "OTC药品必须选择", trigger: "change" }],
    packagingUnit: [{ required: true, message: "包装单位不能为空", trigger: "change" }],
    drugUsage: [{ required: true, message: "药品用法不能为空", trigger: "change" }],
  }
});

const { queryParams, form, rules } = toRefs(data);
/** 详细按钮操作 */
/** 详细按钮操作 */
function handleUpdate(row) {
  reset();
  form.value = row
  // 同时请求入库和出库数据
  Promise.all([
    selectDrugByCode({drugCode:row.drugCode}),
    selectOutDrugByCode({drugCode:row.drugCode})
  ]).then(([inRes, outRes]) => {
    // 合并数据并添加类型标识
    InventoyList.value = [
      ...inRes.data.map(item => ({ ...item })), // 入库数据
      ...outRes.data.map(item => ({ ...item })) // 出库数据
    ];
    console.log(InventoyList.value);
  });
  open.value = true;
  title.value = "查看库存明细";
}

/** 查询药品信息列表 */
function getList() {
  loading.value = true;
  queryParams.value.params = {};
  if (null != daterangeCreationTime && '' != daterangeCreationTime) {
    queryParams.value.params["beginCreationTime"] = daterangeCreationTime.value[0];
    queryParams.value.params["endCreationTime"] = daterangeCreationTime.value[1];
  }
  listDrug(queryParams.value).then(response => {
    drugList.value = response.rows;
    console.log(drugList.value);
    total.value = response.total;
    loading.value = false;
  });
}

/** 查询药品信息分类列表 */
function getlistInformationList() {
  loading.value = true;
  listInformation(queryParams.value).then(response => {
    informationList.value = response.rows;
    // console.log(informationList.value);
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    drugInformationId: null,
    drugCode: null,
    drugBarcode: null,
    drugGenericName: null,
    pinyinCode: null,
    drugCategory: null,
    drugSpecification: null,
    drugForm: null,
    otcFlag: null,
    invoiceItem: null,
    approvalNumber: null,
    drugManufacturer: null,
    drugStatus: null,
    packagingUnit: null,
    basicCoefficient: null,
    basicUnit: null,
    doseCoefficient: null,
    coefficienUnit: null,
    purchasePrice: null,
    retailPrice: null,
    allowBreakage: null,
    allowMemberDiscount: null,
    drugUsage: null,
    singleDose: null,
    frequency: null,
    inventoryLowerLimit: null,
    inventoryUpperLimit: null,
    locationCode: null,
    expiryWarning: null,
    drugDescription: null,
    remarks: null,
    del: null,
    creationTime: null
  };
  
  proxy.resetForm("drugRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  daterangeCreationTime.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}








/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除药品信息编号为"' + _ids + '"的数据项？').then(function() {
    return delDrug(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('drug/drug/export', {
    ...queryParams.value
  }, `drug_${new Date().getTime()}.xlsx`)
}

getList();
getlistInformationList();
</script>
<style>
.order-info {
  padding: 15px;
  background: #f5f7fa;
  border-radius: 4px;
  margin-bottom: 20px;
}

.info-item {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}

.info-item label {
  width: 80px;
  color: #606266;
  flex-shrink: 0;
}

:deep(.el-input),
:deep(.el-select) {
  flex: 1;
}
</style>